import { useEffect, useState, forwardRef, Ref, useRef } from 'react';
import { getApp } from '@inbiz/utils';
import LeftList from './Components/LeftList';
import TableContent from './Components/TableContent';
import { getAppList, getProcessGroupList } from './servers';
import api from './api';
import './index.less';
type IRef = Ref<ReturnType<typeof api>>;

export interface IProps {
  processGroup: boolean;
  callBackEvents?: {
    onExtendsSave?: (params: any) => Promise<any>;
    formatTableData?: (rows: any[]) => any;
  };
  inline: string[];
  exposureConfig: {
    ownership: boolean;
  };
  processGroupSelector?: any[];
  pagesNum: number;
  allowClear?: boolean;
  processType?: boolean;
  ScopeProcess: 'all' | 'app' | 'group';
  defaultOption?: any[];
  processName: boolean;
  toolbar: string[];
  inbiz?: any;
  refs?: any;
  emit?: {
    (type: 'onSave', handleType: 'add' | 'edit', data: object): void;
    (type: 'onSaveAndPublish', handleType: 'add' | 'edit', data: object): void;
    (type: 'onSelectGroup', groupId: string): void;
  };
}

const ProcessManage = (props: IProps) => {
  // 当前分组Key(id)
  const [activeGroupId, $activeGroupId] = useState<string>('');
  // 当前分组详情
  const [activeGroupInfo, $activeGroupInfo] = useState<any>();
  // 左侧数据列表
  const [listData, $listData] = useState<any[]>([]);
  // 全局下分组数据
  const [treeData, $treeData] = useState<any[]>([]);
  // 分组数据加载完成
  const [listLoaded, $listLoaded] = useState(false);
  // 主体表格每行数据
  const [rowData, $rowData] = useState<any>([]);
  const addGroupRef: any = useRef()

  const initd = useRef<number>(1);

  const globalAppInfo = getApp();

  // 初始化获取流程分组数据
  useEffect(() => {
    $activeGroupId('');
    $activeGroupInfo(null)
    if (props.processGroup) {
      getGroupList(true);
    }
  }, []);

  useEffect(() => {
    if (initd.current > 3) {
      if (props.ScopeProcess === 'group') {
        $listData(props.processGroupSelector || []);
        $activeGroupId(props.processGroupSelector?.[0]?.id || '');
        $activeGroupInfo(props.processGroupSelector?.[0] || null)
      } else {
        $activeGroupId('');
        $activeGroupInfo(null)
        props.processGroup && getGroupList(true);
      }
    }
    initd.current = initd.current + 1;
  }, [props.processGroup, props.ScopeProcess, props.processGroupSelector]);

  // 当前为全部应用时，整体分组数据变化时更新当前所选分组所在应用下的分组数据
  useEffect(() => {
    if (props.ScopeProcess == 'all') {
      const record = treeData?.find((i: any) => i?.id == activeGroupInfo?.appId)
      let list: any[] = []
      if (record && Array.isArray(record?.Children)) {
        list = record.Children
      }
      $listData(list)
    }
  }, [treeData, activeGroupInfo])

  // 获取流程分组数据
  const getGroupList = (init?: boolean) => {
    // 跨应用下
    if (props.ScopeProcess != 'app') {
      getAppList().then(async (res: any) => {
        if (Array.isArray(res?.Items) && res.Items.length) {
          let treeList: any[] = res.Items.map((i: any) => ({ ...i, id: i.Id, app: true }))
          if (props.ScopeProcess == 'all') {
            // 添加个置顶假应用来承载不挂在应用下的流程分组
            treeList = [{ id: '6a04037b4f4511ecb1a60242ac120011', AppName: '流程工作台', app: true }, ...treeList]
            const nowGroup: any = await getProcessGroupList({ pageSize: 9999, appId: treeList[0]?.Id || treeList[0]?.id })
            if (Array.isArray(nowGroup?.details?.rows) && nowGroup.details.rows.length) {
              $activeGroupId(nowGroup.details.rows[0]?.id || '')
              $activeGroupInfo(nowGroup?.details?.rows?.[0] || null)
              treeList[0].Children = nowGroup.details.rows
            }
          }
          $treeData(treeList)
        }
      })
      if (props.ScopeProcess == 'all') return
    }
    // 当前应用或自定义
    let params: any = {
      pageSize: 9999,
    };
    if (props.processGroup && props.ScopeProcess === 'app') {
      params.appId = globalAppInfo.AppId;
    }
    getProcessGroupList(params).then((res: any) => {
      if (props.processGroup && props.ScopeProcess === 'group') {
        $listData(props.processGroupSelector || [])
      } else if (res?.details == null) {
        $listData([])
      } else {
        $listData(res?.details?.rows)
      }
      $listLoaded(true)
      // 选中第列表一个
      if (props.processGroup && (init || activeGroupId === '')) {
        if (props.ScopeProcess === 'group') {
          $activeGroupId(props.processGroupSelector?.[0]?.id || '')
          $activeGroupInfo(props.processGroupSelector?.[0] || null)
        } else {
          $activeGroupId(res?.details?.rows?.[0]?.id || '')
          $activeGroupInfo(res?.details?.rows?.[0] || null)
        }
      } else {
        init && $activeGroupId('')
        init && $activeGroupInfo(null)
      }
    });
  };

  return (
    <div className="inbiz-process-management-component">
      {/* 左侧列表 */}
      {props.processGroup && (
        <div className="left-list-box">
          <LeftList
            activeGroupId={activeGroupId}
            $activeGroupId={$activeGroupId}
            activeGroupInfo={activeGroupInfo}
            $activeGroupInfo={$activeGroupInfo}
            listData={listData}
            $listData={$listData}
            $rowData={$rowData}
            getList={getGroupList}
            addGroupRef={addGroupRef}
            treeData={treeData}
            $treeData={$treeData}
            {...props}
          />
        </div>
      )}

      {/* 右侧主体 */}
      <TableContent
        activeGroupId={activeGroupId}
        $activeGroupId={$activeGroupId}
        activeGroupInfo={activeGroupInfo}
        $activeGroupInfo={$activeGroupInfo}
        rowData={rowData}
        $rowData={$rowData}
        listData={listData}
        treeData={treeData}
        $treeData={$treeData}
        refreshGroup={getGroupList}
        listLoaded={listLoaded}
        addGroup={() => addGroupRef.current?.add?.()}
        {...props}
      />
    </div>
  );
};

export default ProcessManage;
